package com.shanjupay.merchant;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.common.util.EncryptUtil;
import com.shanjupay.common.util.QiniuUtils;
import com.shanjupay.merchant.api.dto.MerchantDTO;
import com.shanjupay.merchant.service.FileService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @program: shanjupay
 * @description:
 * @author: Mr.Hkc
 * @create: 2020-08-18 11:38
 **/
@SpringBootApplication
public class MerchantApplicationBootstrap {

    public static void main(String[] args) {
        SpringApplication.run(MerchantApplicationBootstrap.class,args);
        /*Long merchantId = 1295663541289791490L;//填写用于测试的商户id
        //MerchantDTO merchantDTO = merchantService.queryMerchantById(merchantId);
        MerchantDTO merchantDTO = new MerchantDTO();
        merchantDTO.setMobile("18320374738");
        merchantDTO.setUsername("张三");

        JSONObject token = new JSONObject();
        token.put("mobile", merchantDTO.getMobile());
        token.put("user_name", merchantDTO.getUsername());
        token.put("merchantId", merchantId);

        String jwt_token = "Bearer " + EncryptUtil.encodeBase64(JSON.toJSONString(token).getBytes());
        System.out.println(jwt_token);*/
    }

    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        //得到消息转换器
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        //指定消息转换器字符集为UTF-8
        messageConverters.set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }

    @Bean
    public FileService fileService(){
        return new FileService() {
            @Override
            public String upload(byte[] bytes, String filename) throws BusinessException {
                String Qiniu_url = "http://qe7kmmeec.bkt.clouddn.com/";
                try {
                    //调用common工具类
                    QiniuUtils.upload2Qiniu(bytes,filename);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BusinessException(CommonErrorCode.E_100106);
                }
                return Qiniu_url + filename;
            }
        };
    }

}

